package cn.yerly.learning_code.io.bio;



import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import cn.yerly.learning_code.io.entity.MyRequestObject;
import cn.yerly.learning_code.io.entity.MyResponseObject;

/**
 * bio client
 * Created by yerly on 2015/5/11.
 */
public class Client {
    private final static Logger logger = Logger.getLogger(Client.class.getName());
    public static void main(String[] args) throws IOException {
        for (int i = 0; i < 10000; i++) {
            final int idx = i;
            new Thread(new MyRunnable(idx)).start();
        }

    }

    private static final class MyRunnable implements Runnable {

        private final int idx;

        private MyRunnable(int idx) {
            this.idx = idx;
        }

        public void run() {
            Socket s;
            ObjectOutputStream out = null;
            ObjectInputStream in = null;
            try {
                s = new Socket("127.0.0.1", 9999);
                out = new ObjectOutputStream(s.getOutputStream());
                in = new ObjectInputStream(s.getInputStream());
                MyRequestObject myRequestObject = new MyRequestObject("request_" + idx, "request_" + idx);
                logger.log(Level.INFO, myRequestObject.toString());
                out.writeObject(myRequestObject);
                out.flush();
                MyResponseObject myResponseObject = (MyResponseObject) in.readObject();
                logger.log(Level.INFO, myResponseObject.toString());
            } catch (Exception e) {
                logger.log(Level.SEVERE, null, e);
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                }
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }

}

